# -*- coding: utf-8 -*-

from django.shortcuts import render
from django.views.generic import View
from django.http import HttpResponse
from django.db.models import Q

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger

from .models import Course, CourseResource, Video
from operation.models import UserFavorite, CourseComments, UserCourse
from utils.mixin_util import LoginRequiredMixin


class CourseListView(View):
    def get(self, request):
        all_courses = Course.objects.all().order_by('-add_time')

        # 热门课程
        hot_course = Course.objects.all().order_by('-click_nums')[:3]

        # 获取搜索的关键字
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            # 根据关键字忽略大小写来获取课程列表
            all_courses = all_courses.filter(
                Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords) | Q(
                    detail__icontains=search_keywords))

        # 按学习人数或课程数来进行排序
        sort = request.GET.get('sort', '')
        if sort:
            if sort == 'students':
                all_courses.order_by('-students')
            elif sort == 'hot':
                all_courses.order_by('-click_nums')

        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_courses, 6, request=request)
        courses = p.page(page)
        return render(request, 'course-list.html', {
            'courses': courses,
            'sort': sort,
            'hot_course': hot_course
        })


class CourseDetailView(View):
    """
    用户点击课程时跳转至课程详情页
    """

    def get(self, request, course_id):
        course_detail = Course.objects.get(id=int(course_id))
        # 增加课程的点击数
        course_detail.click_nums += 1
        course_detail.save()

        # 通过课程的标签来获得推荐课程
        tag = course_detail.tag
        if tag:
            relate_courses = Course.objects.filter(tag=tag)[:1]
        else:
            relate_courses = []

        course_has_fav = False
        org_has_fav = False

        if request.user.is_authenticated():
            # 判断该用户是否已经收藏该机构
            if UserFavorite.objects.filter(user=request.user, fav_id=course_detail.course_org.id, fav_type=2):
                org_has_fav = True

            # 判断该用户是否已经收藏该课程
            if UserFavorite.objects.filter(user=request.user, fav_id=course_detail.id, fav_type=1):
                course_has_fav = True

        return render(request, 'course-detail.html', {
            'course_detail': course_detail,
            'relate_courses': relate_courses,
            'course_has_fav': course_has_fav,
            'org_has_fav': org_has_fav
        })


class CourseInfoView(LoginRequiredMixin, View):
    """
    用户点击我要学习跳转至该课程章节信息
    """

    def get(self, request, course_id):
        course = Course.objects.get(id=course_id)
        course.students += 1
        course.save()
        # 获取该课程的所有章节
        lessons = course.lesson_set.all()
        # 获取该课程下的所有资源
        all_resources = CourseResource.objects.filter(course=course)

        # 查询当前用户是否已经学习该课程
        has_study = UserCourse.objects.filter(user=request.user, course=course)
        # 没有学习该课程,便加一条数据
        if not has_study:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

        # 获取学了该课程的用户操作对象
        user_courses = UserCourse.objects.filter(course=course)
        # 获取学习该课程的所有用户的id
        user_ids = [user_course.user.id for user_course in user_courses]
        # 通过用户id获取其学的课程
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
        # 获取所有课程id
        course_ids = [user_course.course.id for user_course in all_user_courses]
        study_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')[:4]

        return render(request, 'course-video.html', {
            'course': course,
            'lessons': lessons,
            'all_resources': all_resources,
            'study_courses': study_courses
        })


class CommentsView(LoginRequiredMixin, View):
    """
    课程评论信息
    """

    def get(self, request, course_id):
        course = Course.objects.get(id=course_id)
        # 获取该课程的所有评论
        all_comments = CourseComments.objects.filter(course=course)
        # 获取该课程下的所有资源
        all_resources = CourseResource.objects.filter(course=course)
        return render(request, 'course-comment.html', {
            'course': course,
            'all_resources': all_resources,
            'all_comments': all_comments
        })


class AddCommentView(View):
    """
    axaj添加课程评论
    """

    def post(self, request):
        course_id = request.POST.get('course_id', 0)
        comments = request.POST.get('comments', 0)
        # 判断用户是否登录
        if not request.user.is_authenticated():
            return HttpResponse('{"status":"fail","msg":"用户未登录"}', content_type='application/json')

        if course_id > 0 and comments:
            course_comments = CourseComments()
            course = Course.objects.get(id=course_id)
            course_comments.course = course
            course_comments.comment = comments
            course_comments.user = request.user
            course_comments.save()
            return HttpResponse('{"status":"success","msg":"添加评论成功"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail","msg":"添加评论失败"}', content_type='application/json')


class VideoPlayView(View):
    """
    视频播放逻辑
    """

    def get(self, request, video_id):
        video = Video.objects.get(id=int(video_id))
        # 该视频所属的课程
        course = video.lesson.course
        # 获取该课程的所有章节
        lessons = course.lesson_set.all()
        # 获取该课程下的所有资源
        all_resources = CourseResource.objects.filter(course=course)

        # 查询当前用户是否已经学习该课程
        has_study = UserCourse.objects.filter(user=request.user, course=course)
        # 没有学习该课程,便加一条数据
        if not has_study:
            user_course = UserCourse(user=request.user, course=course)
            user_course.save()

        # 获取学了该课程的用户操作对象
        user_courses = UserCourse.objects.filter(course=course)
        # 获取学习该课程的所有用户的id
        user_ids = [user_course.user.id for user_course in user_courses]
        # 通过用户id获取其学的课程
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)
        # 获取所有课程id
        course_ids = [user_course.course.id for user_course in all_user_courses]
        study_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')[:4]

        return render(request, 'course-player.html', {
            'course': course,
            'lessons': lessons,
            'all_resources': all_resources,
            'study_courses': study_courses,
            'video': video
        })
